﻿#include <QApplication>
#include <QFontDatabase>
#include <QTranslator>
#include <QTextCodec>
#include <QSplashScreen>
#include <QResource>
#include <QDir>
#include <QSharedMemory>

#define _IN_MAIN_CPP

#include "main.h"
#include "mctype/patternsingleboard/mainUI/mainwidget.h"

QString switchLanguage(int language,QDir appPath)
{
    QString sourcePath,targetPath;
    targetPath = appPath.path() + appPath.separator() + "language.qm";
    switch (language)
    {
    case 0://中文
        sourcePath = appPath.path() + appPath.separator() + "chinese.qm";
        break;
    case 1://英文
        sourcePath = appPath.path() + appPath.separator() + "english.qm";
        break;
    case 2://西班牙文
        sourcePath = appPath.path() + appPath.separator() + "spanish.qm";
        break;
    case 3://孟加拉文
        sourcePath = appPath.path() + appPath.separator() + "bengal.qm";
        break;
    case 4://土耳其文
        sourcePath = appPath.path() + appPath.separator() + "turkey.qm";
        break;
    case 5://丹麦文
        sourcePath = appPath.path() + appPath.separator() + "denmark.qm";
        break;
    case 6://越南文
        sourcePath = appPath.path() + appPath.separator() + "vietnamese.qm";
        break;
    default://中文
        sourcePath = appPath.path() + appPath.separator() + "chinese.qm";
        break;
    }

    QFile::remove(targetPath);
    QFile::copy(sourcePath,targetPath);
#ifdef Q_OS_LINUX
    system("sync");
#endif
    return targetPath;
}

void setMcMainWindow(QApplication &app, QSplashScreen *splash, s16 HMIDecrypt, s16 connectMode)
{\

    //创建主窗口
    MainWidget mainwindow;
    //初始化主窗口
    mainwindow.initMcTypeWindows();
    mainwindow.initAllWindows(HMIDecrypt,connectMode);
    mainwindow.show();//显示窗口
    //mainwindow.setWindowIcon(QIcon(":/images/1024x600/rp.png"));
    splash->finish(NULL);
    app.exec();//开始执行应用程序

}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);//此处必须用QApplication，否则QSplashScreen不能使用
    QSharedMemory shared_memory;
    shared_memory.setKey(QString("main_window"));//设置固定共享内存段的key值
    if(shared_memory.attach())   //尝试将进程附加到该共享内存段,避免windows下重开程序
    {
        return 0;
    }
    //LINUX环境下 设置全局鼠标光标-使用 Qt::BlankCursor 时，鼠标光标将变得不可见
#ifdef Q_OS_LINUX
    QApplication::setOverrideCursor(Qt::BlankCursor);
#endif

    //支持中文编码
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    //文件路径
    QDir apppath(qApp->applicationDirPath());

    //配置文件路径
    QString configfile;
    configfile = apppath.path() + apppath.separator() + "config.ini";

    //读入配置
    g_pSettings = new Settings();
    g_pSettings->loadSetting(configfile);
    QFile iniFile(configfile);
    int language = 0;
    s16 connectMode = 0;
    s16 gatewayConnectMode = 0;

    if(!iniFile.exists())//配置文件不存在
    {
        g_pSettings->writeToIniFile("Pattern/name","");
        g_pSettings->writeToIniFile("HMI/resolution",resolution1006);
        g_pSettings->writeToIniFile("HMI/theme",theme1);
        g_pSettings->writeToIniFile("HMI/language",chinese);
        g_pSettings->writeToIniFile("HMI/FrontSize",FONTSIZE);
        g_pSettings->writeToIniFile("HMI/machineType",MACHINE_HIGHSPEEDSINGLEQUI);
        g_pSettings->writeToIniFile("HMI/productType",PRODUCT_NULL);
        g_pSettings->writeToIniFile("HMI/debugMode",nodebugMode);//界面调试模式
        g_pSettings->writeToIniFile("HMI/waterMark",1);//0:主背景图不带水印 1:主背景图带水印
        g_pSettings->writeToIniFile("HMI/paraSort",0);//0:参数不分类显示 1:参数分类显示

        g_pSettings->writeToIniFile("HMI/connectMode",0);//连接方式(通讯方式，网口或串口)
        g_pSettings->writeToIniFile("HMI/passwordOne",g_passwordOne);
        g_pSettings->writeToIniFile("IOT/gatewayConnectMode",0);//网关连接方式(连接方式，网口或串口)
        g_pSettings->writeToIniFile("IOT/rackNumber",0);//机架号

        g_pSettings->writeToIniFile("DateTime/second",0);

        //平板切割算法
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutMinstStp", 5);   // 拟合小针步
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutLineMinStp", 20); // 直线最小步长
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutLineMaxStp", 800);// 直线最大步长
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutRoudAng", 3000);   // 圆弧转角判断度数
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutRoudStp", 10);      // 圆弧补偿步长
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cut1Radius", 50);   // 切刀1圆弧补偿半径
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cut2Radius", 50);       // 切刀2圆弧补偿半径

        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutSpdMinpps", 10);               // 最小切割速度, 范围 1--100，单位mm/s，默认 10
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutSpdMaxpps", 1000);         // 最大切割速度, 范围 1--1200，单位mm/s，默认 1000
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutAddPpsg", 500);                  // 切割加速度, 范围 1--4000，单位mm/s2，默认 500
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutSlowAngle", 3000);        // 切割降速最小偏差角度，范围 0--18000，单位 0.01度，默认 3000
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutWorkMinadd", 1);               // 工作最小加速度 默认1

        //平板切割机定位点
        g_pSettings->writeToIniFile("FlatPanel/AnchorPointX", 0);
        g_pSettings->writeToIniFile("FlatPanel/AnchorPointY", 0);

        //飞行切割平板切割机
        g_pSettings->writeToIniFile("FlatPanelAlgorithm/cutCrutchAng", 60);// 拐点转角判断度数
        //g_pSettings->writeToIniFile("HMI/DATA_FORMATE", DATA_DS16);// 数据传输方式
        g_pSettings->writeToIniFile("HMI/resolution",resolution1006);

        //写入机头断线次数
        g_pSettings->writeToIniFile("HeadBreakLineNum",0);

        //DATA_FORMATE = DATA_DS16;

        g_emResolut = resolution1006;
        g_emTheme = theme1;
        language = chinese;
        g_emDebugMode = nodebugMode;
        g_emMacType = MACHINE_HIGHSPEEDSINGLEQUI;
        g_emProductType = PRODUCT_NULL;
        g_passwordOne =  PASSWORD_ONE;
        g_fontsize = FONTSIZE;
    }
    else
    {
        int frontSize =  g_pSettings->readFromIniFile("HMI/FrontSize").toInt();
        if((4 > frontSize) || (frontSize > 32) )
        {
            g_pSettings->writeToIniFile("HMI/FrontSize",FONTSIZE);
            g_fontsize = FONTSIZE;
        }
        g_fontsize = g_pSettings->readFromIniFile("HMI/FrontSize").toInt();

        g_emResolut = (Resolution)(g_pSettings->readFromIniFile("HMI/resolution").toInt());
        g_emTheme = (Theme)(g_pSettings->readFromIniFile("HMI/theme").toInt());
        //这个情况是，存在配置文件的时候，很可能是只有DateTime/second，读不到主题，就是0（图片加载不出来），二级密码也会没有

        //为了防止配置文件里没有debugMode时升级黑屏，因为界面调试模式是后来新加的，之前版本的配置文件里没有，兼容之前的版本  -rq
        QString debugModeStr = "HMI/debugMode";
        if(g_pSettings->ifKeyExists(debugModeStr) == true)
        {
            g_emDebugMode =(DebugMode)(g_pSettings->readFromIniFile("HMI/debugMode").toInt());//如果存在配置文件，并且有这个key就读配置文件里的调试模式的值
        }
        else
        {
            g_pSettings->writeToIniFile("HMI/debugMode",nodebugMode);//界面调试模式
            g_emDebugMode = nodebugMode;
        }
        language = g_pSettings->readFromIniFile("HMI/language").toInt();
        g_emDebugMode =(DebugMode)(g_pSettings->readFromIniFile("HMI/debugMode").toInt());//如果存在配置文件，就读配置文件里的调试模式的值
        g_emMacType = (MachineType)(g_pSettings->readFromIniFile("HMI/machineType").toInt());
        g_emProductType = (ProductType)(g_pSettings->readFromIniFile("HMI/productType").toInt());
        connectMode = g_pSettings->readFromIniFile("HMI/connectMode").toInt();
        g_passwordOne = g_pSettings->readFromIniFile("HMI/passwordOne").toString();
        if(g_passwordOne.isEmpty())
            g_passwordOne =  PASSWORD_ONE;
        gatewayConnectMode = g_pSettings->readFromIniFile("IOT/gatewayConnectMode").toInt();


        //        int data_form = g_pSettings->readFromIniFile("HMI/DATA_FORMATE").toInt();// 数据传输方式
        //        DATA_FORMATE = data_form;
    }

    //自动获取屏幕分辨率
#ifdef Q_OS_LINUX
    QDesktopWidget * desktop = QApplication::desktop();
    QRect screenRect = desktop->screenGeometry();
    int width = screenRect.width();
    int height = screenRect.height();
    if(width == 1920 && height == 1080)
    {
        g_emResolut = resolution1910;
    }
    else if(width == 1024 && height == 600)
    {
        g_emResolut = resolution1006;
    }
    else if(width == 800 && height == 480)
    {
        g_emResolut = resolution0804;
    }

#endif




    //多语言翻译
    QString languageFile = switchLanguage(language,apppath);
    QTranslator translator;
    translator.load(languageFile);
    app.installTranslator(&translator);

    //资源文件
    QString resourcefile = apppath.path() + apppath.separator() + "nxcui.rcc";
    QResource::registerResource(resourcefile);

    //启动画面
    QSplashScreen *splash = new QSplashScreen;
    if(g_emResolut == resolution1006)
    {
        splash->setPixmap(QPixmap(":/images/startlogo1006.png"));
    }
    else if(g_emResolut == resolution0804)
    {
        splash->setPixmap(QPixmap(":/images/startlogo1006.png"));
    }
    else if(g_emResolut == resolution1910)
    {
        splash->setPixmap(QPixmap(":/images/startlogo1910.png"));
    }


    QFont font;
    font.setPixelSize(20);
    splash->setFont(font);
    //splash->move(0,0);
    splash->move(0+g_mainWidgetPos.x(),0+g_mainWidgetPos.y());
    int waterMark = g_pSettings->readFromIniFile("HMI/waterMark").toInt();//是否带水印
    if(waterMark==1)//带logo
    {
        splash->show();//显示启动画面
    }

    //检测界面解密的配置文件是否存在
    //界面解密配置文件路径
    s16 HMIDecrypt = 1;//1代表已授权解密过，0代表未授权解密过
    QString HMIDecryptConfigfile;
    HMIDecryptConfigfile = apppath.path() + apppath.separator() + "HMIDecryptConfig.ini";
    QFile HMIDecryptIniFile(HMIDecryptConfigfile);
    if(!HMIDecryptIniFile.exists())//不存在界面解密的文件(已发机器),可与主板建立连接
    {
        HMIDecrypt = 1;
    }
    else//存在界面解密的文件,判断是否解密过来决定是否与主板建立连接
    {
        QSettings iniSetting(HMIDecryptConfigfile, QSettings::IniFormat);
        HMIDecrypt = iniSetting.value("HMIDecrypt/ifdecrypt").toInt();
    }

    g_pMachine = NULL;
    QString mcConfigfile;
    mcConfigfile = apppath.path() + apppath.separator() + "mcconfig.ini";

    g_pMachine = new Machine();   //创建下位机通讯
    g_pMachine->initConnectMode(connectMode);//初始化通讯连接方式
    g_pMachine->setComportName(""); //名字为空
    g_pMachine->setConfigFileName(mcConfigfile);//配置文件
    if(HMIDecrypt != 0)
    {
        g_pMachine->startCommunication();//启动线程
    }

    //物联网客户端与mqtt网关服务器建立连接
    g_pLotMachine = NULL;
    QString lotConfigfile;
    lotConfigfile = apppath.path() + apppath.separator() + "lotconfig.ini";
    g_pLotMachine = new LotMachine();   //创建网关通讯
    g_pLotMachine->initConnectMode(gatewayConnectMode);//初始化通讯连接方式
    g_pLotMachine->setComportName("");
    g_pLotMachine->setConfigFileName(lotConfigfile);
    g_pLotMachine->startCommunication();

    g_pCurEmbData = new EmbData();

#ifdef Q_OS_WIN
    //win下防止多个程序打开
    if(shared_memory.create(1)) //创建1byte的共享内存段
    {
        setMcMainWindow(app,splash,HMIDecrypt,connectMode);
    }
#endif

#ifdef Q_OS_LINUX
    setMcMainWindow(app,splash,HMIDecrypt,connectMode);
#endif

    delete splash;
    delete g_pSettings;
    delete g_pMachine;
    delete g_pCurEmbData;
    return 0;
}
